//My C++ incdlues
#include <iostream>
#include <cmath>

//My own headers
#include "server.h"
#include "polygon.h"

#ifdef SAVE_TRIGGER
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif /* SAVE_TRIGGER */
// #define DEBUG_SUMMARY

pthread_mutex_t data_mutex;

directions direc;

void processFrame(Mat& image, RectangleScanner& scanner)
{
    RotatedRect rectangle;
    directions new_direc;
#ifdef SAVE_IMAGES
    bool save_image = true;
#endif /* SAVE_IMAGES */

#if defined(SAVE_IMAGES) && defined(SAVE_TRIGGER)
    save_image = false;
    struct stat st;
    if ((stat("/tmp/save_images", &st)) == 0) {
        save_image = true;
    }
#endif 

#ifdef SAVE_IMAGES
    if (save_image) {
        // housekeeping saved orginal frame
        saveFrame((char*)"raw_", &image);
    }
#endif /* SAVE_IMAGES */

    // main logic of frame image processing
    scanner.SetImage(image);
    scanner.ChooseRectangle();
    // end of logic of frame image processing
    
#ifdef SAVE_IMAGES
    if (save_image) {
        // housekeeping save frame after proccessing
        if (scanner.saw_rect) {
            saveFrame((char *)"final_", &(scanner.src_rects));
        } else {
            saveFrame((char *)"nothing_", &(scanner.src_rects));
        }
    }
#endif /* SAVE_IMAGES */

    if (scanner.saw_rect) {        
        new_direc.status = 0;
	new_direc.dynamic_on = scanner.dynamic_on;

#ifdef DEBUG_SUMMARY
        cout << "Distance is " << new_direc.dist << endl;
        cout << "Dynamic on is  " << new_direc.dynamic_on << endl;
        cout << "Status is " << new_direc.status << endl << endl;
#endif /* DEBUG_SUMMARY */
    } else {
        new_direc.status = 5;

#ifdef DEBUG_SUMMARY
        cout << "Nothing detected: Status is " << new_direc.status << endl;
#endif /* DEBUG_SUMMARY */
    }
    pthread_mutex_lock(&data_mutex); //Lock structure direc
    direc = new_direc;
    pthread_mutex_unlock(&data_mutex); //Unlock structure direc
}   
